package cn.careerx.app.common.models;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.SqlRow;
import com.avaje.ebean.SqlUpdate;

import libs.CodecNCrypto;
import redis.clients.jedis.Jedis;

public class UserSkill implements Serializable{

	private static final long serialVersionUID = 7678857061398550561L;
	
	private String id;
	private Integer level;
	
	//Redis keys
	private static final String USER_SKILLLEVEL_KEY = "user.skillLevel:";
	private static final String USER_OCC_SKILLSET_LEVEL_KEY = "user.occupation.skillset:";
	
	public static UserSkill create(){
		return new UserSkill();
	}
	
	public static List<UserSkill> getUserSkillsByUserId(Database db,Jedis jedis,String userId){
		List<UserSkill> result= new ArrayList<UserSkill>();
		String key  = USER_SKILLLEVEL_KEY+userId;
		if(jedis.exists(key)){
			Map<String,String> map = jedis.hgetAll(key);
			for(String skillId : map.keySet()){
				UserSkill us = UserSkill.create().setId(skillId).setLevel(Integer.valueOf(map.get(skillId)));
				result.add(us);
			}
			return result;
		}
		EbeanServer es  = db.getDbByPartitionKey("CAREERX", "");
		List<SqlRow> rows = es.createSqlQuery("SELECT * FROM  CX_USER_SKILL WHERE USER_ID=? ORDER BY SKILL_LEVEL DESC")
								.setParameter(1, userId).findList();
		for(SqlRow row : rows){
			UserSkill skillTemp = UserSkill.create()
								   .setId(row.getString("SKILL_ID"))
								   .setLevel(row.getInteger("SKILL_LEVEL"));
			jedis.hset(key, skillTemp.getId(), String.valueOf(skillTemp.getLevel()));
			result.add(skillTemp);
		}
		return result;
	}
	
	//FIXME 修改用户技能等级以后改为先修改redis中的值，最后批量更新到数据库中
	public static int updateUserSkill(Database db, Jedis jedis, String userId, String skillId, String skillLevel) {
		String keyu  = USER_SKILLLEVEL_KEY+userId;
		EbeanServer es = db.getDbByPartitionKey("CAREERX", "");
		SqlRow row = es.createSqlQuery("SELECT COUNT(1) AS C FROM CX_USER_SKILL WHERE USER_ID=? AND SKILL_ID=?").setParameter(1, userId).setParameter(2, skillId).findUnique();
		SqlUpdate sqlUpdate;
		if(row.getInteger("C")==0){
			sqlUpdate = es.createSqlUpdate("INSERT INTO CX_USER_SKILL(ID,USER_ID,SKILL_ID,SKILL_LEVEL) VALUES(?,?,?,?)")
							.setParameter(1, CodecNCrypto.UUID()).setParameter(2, userId).setParameter(3, skillId).setParameter(4, skillLevel);
		}else{
			sqlUpdate = es.createSqlUpdate("UPDATE CX_USER_SKILL SET SKILL_LEVEL=? WHERE USER_ID=? AND SKILL_ID=?")
						.setParameter(1, skillLevel).setParameter(2, userId).setParameter(3, skillId);
		}
		int i = sqlUpdate.execute();
		if(i>0){
			jedis.hset(keyu, skillId, skillLevel);
		}
		return i;
	}
	
	//FIXME  之后更改为批量同步到数据库
	public static long saveOrUpdateUserOcc(Database db, Jedis jedis, String occId,Integer occLevel,String userId) {
		String key = USER_OCC_SKILLSET_LEVEL_KEY+userId;
		long i = 0;
		
		EbeanServer es = db.getDbByPartitionKey("CAREERX", null);
		SqlRow row = es.createSqlQuery("SELECT COUNT(1) AS C FROM CX_USER_OCC WHERE USER_ID=? AND OCC_ID=?")
					 .setParameter(1, userId).setParameter(2, occId).findUnique();
		if(row.getInteger("C") > 0){
			i = es.createSqlUpdate("UPDATE CX_USER_OCC SET OCC_LEVEL=? WHERE USER_ID=? AND OCC_ID=?")
			  .setParameter(1, occLevel).setParameter(2, userId).setParameter(3, occId)
			  .execute();
		}else{
			i = es.createSqlUpdate("INSERT INTO CX_USER_OCC (ID,USER_ID,OCC_ID,OCC_LEVEL) VALUES(?,?,?,?)")
					  .setParameter(1, CodecNCrypto.UUID()).setParameter(2, userId)
					  .setParameter(3, occId).setParameter(4, occLevel).execute();
		}
		if(i>0){
			jedis.hset(key, "occId", occId);
			jedis.hset(key, "occLevel", String.valueOf(occLevel));
		}
		return i;
	}

	public String getId() {
		return id == null ? "" : id;
	}

	public UserSkill setId(String id) {
		this.id = id;
		return this;
	}

	public Integer getLevel() {
		return level == null ? 0 : level;
	}

	public UserSkill setLevel(Integer level) {
		this.level = level;
		return this;
	}
}
